<?php
/*
* Author: Jason ZHENG <zmj522008@hotmil.com>
* Date  : 2018/05/17
* Class : Homepage 首页
*/
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Session;

class Homepage extends Controller
{ 
	//获取首页数据统计
	public function index()
	{   
		$returnData = [
			'generalBusiness'  		=> $this->get_general_business(),
			'storageAgeAnalysis' 	=> $this->get_storage_age(),
			'purchaseSourceStats'	=> $this->get_purchase_sources_stats(),
			'salesmenRecord'		=> $this->get_salsemen_record(),
		];

		return ['code'=>666, 'msg'=>'Homepage data stats/首页数据统计', 'data'=> $returnData];
	}

	//获取商家概况
	public function get_general_business()
	{
		$incomeReceive 				= $this->get_income_receive();
		$buyersOrdersCountOnline 	= $this->get_ordersCount_buyersCount_online();
		$buyersOrdersCountOffline 	= $this->get_ordersCount_buyersCount_offline();
		$refund 					= $this->get_refund();
		$productsStorage 			= $this->get_products_storage();
		$productsPrecurement 		= $this->get_procurement();
		$procurementTurnaround 		= $this->get_procurement_turnaround();

		return array_merge($incomeReceive,$buyersOrdersCountOnline, $buyersOrdersCountOffline, $refund, $productsStorage,$productsPrecurement, $procurementTurnaround);
	}

	//获取总成交金额（totalIncome）和总收入金额（totalReceive）
	public function get_income_receive()
	{ 
		$conditions = [
			'o.business_id' 			=> $this->business_id,
			'o.state'					=> 0
		];
		$orders = Db::table('orders')
				->alias('o')
				->join('orders_info oi','o.batchcode = oi.batchcode','LEFT')
				->where($conditions)
				->where(['o.status' => ['neq' , 9]])
				->select();
		$totleIncome = 0;
		$totleReceive = 0;
		foreach ($orders as $order) {
			$totleIncome = $totleIncome + $order['total_price'];
			if($order['is_prepay'] == null){
				$totleReceive = $totleReceive + $order['total_price'];
			}else{
				$totleReceive = $totleReceive + $order['deposit'];
			}
		}

		return ['totalIncome' => round($totleIncome,2), 'totalReceive' => round($totleReceive,2)];
	}

	//获取线上支付买家数（buyersCountOnline）和支付订单数（ordersCountOnline）
	public function get_ordersCount_buyersCount_online()
	{ 
		$buyersHasIdCount = Db::table('orders')
					->where(['business_id' => $this->business_id, 'type' => 1, 'state' => 0])
					->where(['user_id' => ['neq', null]])
					->group('user_id')
					->count();
		$buyersNoIdCount = Db::table('orders')
					->where(['business_id' => $this->business_id, 'type' => 1, 'state' => 0])
					->where(['user_id'=>null])
					->count();
		$ordersCount = Db::table('orders')
					->where(['business_id' => $this->business_id, 'type' => 1, 'state' => 0])
					->count();
		return ['buyersCountOnline' => round($buyersHasIdCount+$buyersNoIdCount,2), 'ordersCountOnline' => round($ordersCount,2) ];
	}

	//获取线下支付买家数（buyersCountOffline）和支付订单数（ordersCountOffilne）
	public function get_ordersCount_buyersCount_offline()
	{
		$buyersHasIdCount = Db::table('orders')
					->where(['business_id' => $this->business_id, 'type' => 0, 'state' => 0])
					->where(['user_id' => ['neq', null]])
					->group('user_id')
					->count();
		$buyersNoIdCount = Db::table('orders')
					->where(['business_id' => $this->business_id, 'type' => 0, 'state' => 0])
					->where(['user_id'=>null])
					->count();
		$ordersCount = Db::table('orders')
					->where(['business_id' => $this->business_id, 'type' => 0, 'state' => 0])
					->count();

		return ['buyersCountOffline' => round($buyersHasIdCount+$buyersNoIdCount,2), 'ordersCountOffilne' => round($ordersCount,2) ];
	}

	//获取退款笔数（refundOrdersCount）和退款金额总数（refundMoneyTotal）
	public function get_refund()
	{
		$refundOrders = Db::table('orders')
					->alias('o')
					->join('orders_info oi','o.batchcode = oi.batchcode','LEFT')
					->where(['o.business_id' => $this->business_id, 'o.state' => 0])
					->where(['oi.status' => 9])
					->select();

		$refundMoneyTotal = 0;
		foreach ($refundOrders as $refundOrder) {
			$refundMoneyTotal = $refundMoneyTotal + $refundOrder['total_price']; 
		}

		return ['refundOrdersCount' => round(count($refundOrders),2), 'refundMoneyTotal' => round($refundMoneyTotal,2)];
	}

	//获取库存商品数量和数量总金额
	public function get_products_storage()
	{
		$products_storage = Db::table('product')
							->where(['business_id' => $this->business_id, 'is_shelf' => 1, 'state' => 0])
							->select();

		$storageProductsNumber 	= 0;
		$storageProductsMoney 	= 0;
		foreach ($products_storage as $product) {
			$storageProductsNumber 	= $storageProductsNumber + $product['stock'];
			$storageProductsMoney 	= $storageProductsMoney + $product['stock']*$product['cost_price'];
		}

		return ['storageProductsNumber' => round($storageProductsNumber,2), 'storageProductMoney' => round($storageProductsMoney,2)];
	}

	//获取回收资金
	public function get_procurement()
	{
		$products_procurement = Db::table('product')
							->where(['business_id' => $this->business_id, 'procurement_status'=> 1, 'is_shelf' => 1,'state' => 0])
							->select();

		$procurementMoney = 0;
		foreach ($products_procurement as $product) {
			$procurementMoney = $procurementMoney + $product['cost_price'];
		}
		return ['procurementMoney' => round($procurementMoney,2)];
	}

	// 获取30天内（上个月）回收周转天数和周转率
	// 周转率   = 月销售成功的累积回收成本/（期初的回收库存在库成本+期末的回收在库成本）/2
	// 周转天数  = 30/周转率 
	public function get_procurement_turnaround()
	{ 
		$productsStart = Db::table('product')
						->where(['business_id' => $this->business_id, 'procurement_status'=> 1, 'is_shelf' => ['neq' , 4], 'state' => 0])
						->where('createtine','<=', date('Y-'.(date('m')-1).'-01', time()))
						->select();

		$productsEnd   = Db::table('product')
						->where(['business_id' => $this->business_id, 'procurement_status'=> 1, 'is_shelf' => ['neq' , 4], 'state' => 0])
						->where('createtine','<=', date('Y-'.(date('m')-1).'-30', time()))
						->select();

 		//期初的回收库存在库成本
		$originalCost = 0;
		foreach ($productsStart as $productStart) {
			$originalCost = $originalCost + $productStart['cost_price'];
		}
		//期末的回收在库成本
		$finalCost = 0;
		foreach ($productsEnd as $productEnd) {
			$finalCost = $finalCost + $productEnd['cost_price'];
		}

		// 回收平均成本
		$costAvg = ($originalCost + $finalCost)/2;

		//30天内回收的商品订单
		$procurementOrders = Db::table('orders')
							->alias('o')
							->join('orders_info oi', 'o.batchcode = oi.batchcode', 'LEFT')
							->where(['o.business_id' => $this->business_id, 'oi.procurement_status'=> 1, 'oi.is_nursing' => 0, 'o.state' => 0])
							->where('o.createtime','>=', date('Y-'.(date('m')-1).'-01', time()))
							->where('o.createtime','<=', date('Y-'.(date('m')-1).'-30', time()))
							->select();

		// 月销售成功的累积回收成本
		$precurementOrdersPriceTotal = 0;
		foreach ($procurementOrders as $procurementOrder) 
		{
			$precurementOrdersPriceTotal = $precurementOrdersPriceTotal + $procurementOrder['price'];
		}

		$turnaroundRatio = $costAvg == 0 ? 0 : $precurementOrdersPriceTotal/$costAvg;
		$turnaroundDays  = $turnaroundRatio == 0 ? 0 : 30/$turnaroundRatio;

		return ['turnaroundRatio' => round($turnaroundRatio,4), 'turnaroundDays' => $turnaroundDays];
	}

	//获取库龄分析
	public function get_storage_age()
	{
		//获取0-90天库龄的回收商品
		$products = Db::table('product')
					->where(['business_id' => $this->business_id, 'state' => 0, 'procurement_status' => 1,'is_shelf' => 1])
					->where('createtine','>=', date('Y-m-d H:i:s', strtotime('-90 days')))
					->select(); 

		$productsGroupByDate = [];
		foreach ($products as $product) {
			$productCreateDate = explode(' ', $product['createtine'])[0];
			$productsGroupByDate[$productCreateDate][] = $product;
		}

		$stats = [];
		foreach ($productsGroupByDate as $date => $products) {
			$stats [] = [
				'date' 						=> $date,
				'productsNumberTotal' 		=> $this->get_products_number_total($products),
				//'productsPriceTotal' 		=> $this->get_products_price_total($products),
				'procurementPriceTotal' 	=> $this->get_products_procurement_price_total($products),
			];
		}

		$storageStats = [];
		for ($day=1; $day <=90; $day++) { 
			$storageStats[$day] = array_values(
												array_filter(
													$stats, 
													function($s) use($day) 
													{
														return $s['date'] == date('Y-m-d', strtotime('-'.$day.' days'));
													}
												)
									);
		} 

		$total['1-15']  = $this->get_products_total_stats_by_period($storageStats, $f=1, $e=15);
		$total['16-30'] = $this->get_products_total_stats_by_period($storageStats, $f=16, $e=30);
		$total['31-45'] = $this->get_products_total_stats_by_period($storageStats, $f=31, $e=45);
		$total['46-60'] = $this->get_products_total_stats_by_period($storageStats, $f=46, $e=60);
		$total['61-75'] = $this->get_products_total_stats_by_period($storageStats, $f=61, $e=75);
		$total['76-90'] = $this->get_products_total_stats_by_period($storageStats, $f=76, $e=90);
		
		return ['storageStats' => $total];
	}

	public function get_products_total_stats_by_period($storageStats, $f=1, $e=15)
	{
		$productsNumberTotal   = 0;
		//$productsPriceTotal 	= 0;
		$procurementPriceTotal = 0;
		for($i=$f; $i <=$e; $i++)
		{
			foreach($storageStats[$i] as $sto ){ 
			   if(isset($sto['productsNumberTotal'])){
			    	$productsNumberTotal 	= $productsNumberTotal + $sto['productsNumberTotal'];
			    }
			    // if(isset($sto['productsPriceTotal'])){
			    // 	$productsPriceTotal 	= $productsPriceTotal + $sto['productsPriceTotal'];
			    // }
			    if(isset($sto['procurementPriceTotal'])){
			    	$procurementPriceTotal 	= $procurementPriceTotal + $sto['procurementPriceTotal'];
			    }
			}
			$i++;
		}

		return $total = [
			'productsNumberTotal'   => $productsNumberTotal,
			//'productsPriceTotal'	=> $productsPriceTotal,
			'procurementPriceTotal'	=> $procurementPriceTotal,
		];
	}

	//获取商品总库存数
	public function get_products_number_total($products)
	{
		$total = 0;
		foreach ($products as $product) {
			$total = $total+$product['stock'];
		}
		return $total;
	}

	//获取商品库存总资金数
	// public function get_products_price_total($products)
	// {
	// 	$total = 0;
	// 	foreach ($products as $product) {
	// 		$total = $total+$product['price']*$product['stock'];
	// 	}
	// 	return $total;
	// }

	//获取商品库存总回收资金数
	public function get_products_procurement_price_total($products)
	{
		$total = 0;
		foreach ($products as $product) {
			$total = $total+$product['cost_price']*$product['stock'];
		}
		return $total;
	}

	// 获取采购类型饼状图
	public function get_purchase_sources_stats()
	{
		$products = Db::table('product')
					->where(['business_id' => $this->business_id, 'state' => 0])
					->select(); 
		// 采购来源
		$purchaseSources = Db::table('perchase_source')
							->where(['state'=>0])
							->select(); 
		$purchaseSourceStats = [];
		foreach ($purchaseSources as $k => $purchaseSource) {
			$purchaseSourceStats[$k]['name'] 	= $purchaseSource['value'];
			$purchaseSourceStats[$k]['count'] 	= count(array_values(array_filter($products, function($p)use($purchaseSource) {return $p['procurement_status'] == $purchaseSource['id']; })));
		}

		return $purchaseSourceStats;
	}

	// 获取员工销售记录
	public function get_salsemen_record()
	{
		//获取员工里面的销售员
		$salsemen = Db::table('staff')
					->where(['business_id' => $this->business_id,'state'=>0])
					->select(); 

		$salsemenStats = [];
		foreach ($salsemen as $key => $salesman) {
			$orders = Db::table('orders')
							->alias('o')
							->join('orders_info oi', 'o.batchcode = oi.batchcode', 'LEFT')
							->where(['o.business_id' => $this->business_id,'oi.staff_id' => $salesman['user_id'], 'oi.is_nursing' => 0, 'o.state' => 0])
							->where('o.createtime','>=', date('Y-m-d 00:00:00', time()))
							->where('o.createtime','<=', date('Y-m-d 23:59:59', time()))
							->select();

			// $customerCount = Db::table('orders')
			// 				->alias('o')
			// 				->join('orders_info oi', 'o.batchcode = oi.batchcode', 'LEFT')
			// 				->where(['o.business_id' => $this->business_id, 'oi.procurement_status'=> 1,'oi.staff_id' => $salesman['user_id'], 'oi.is_nursing' => 0, 'o.state' => 0])
			// 				->group('o.user_id')
			// 				->count();
			$salseTotalMoney = 0;
			foreach ($orders as $key => $order) {
				$salseTotalMoney = $salseTotalMoney + $order['price'] + $order['deposit'] + $order['nursing_income'];
			}

			$salseCostMoney = 0;
			foreach ($orders as $key => $order) {
				$salseCostMoney = $salseCostMoney + $order['original_price'] + $order['nursing_fee'] + $order['other_fee'];
			}
			$salsemenStats [] = [
					'user_id'  				=> $salesman['user_id'],
					'name'					=> $salesman['name'],
					'salseTotalMoney' 		=> $salseTotalMoney,
					'profitMoney'			=> $salseTotalMoney-$salseCostMoney,
					//'customerNumTotal' 		=> $customerCount,
			];				
		}
		return ['salsemenStats' => $this->insertSort($salsemenStats)];
	}

	// 根据利润降序排列
	public function insertSort($arr) 
	{
	    $len=count($arr); 
	    for($i=1 ; $i<$len; $i++) {
	        $tmp = $arr[$i];
	        //内层循环控制，比较并插入
	        for($j=$i-1;$j>=0;$j--) {
	            if($tmp['profitMoney'] > $arr[$j]['profitMoney']) {
	                //发现插入的元素要大，交换位置，将后边的元素与前面的元素互换
	                $arr[$j+1] = $arr[$j];
	                $arr[$j] = $tmp;
	            } else {
	                //如果碰到不需要移动的元素，由于是已经排序好是数组，则前面的就不需要再次比较了。
	                break;
	            }
	        }
	    }
	    return $arr;
	}


}